﻿using CefSharp;
using CefSharp.Wpf;
using System;
using System.Configuration;
using System.Windows;
using System.Windows.Controls;

namespace BrowserXP
{
    /// <summary>
    /// BrowserWindow.xaml 的交互逻辑
    /// </summary>
    public partial class BrowserWindow : Window
    {
        string mUrl = null;
        ChromiumWebBrowser browser = null;
        public BrowserWindow()
        {
            if (mUrl == null)
                mUrl = ConfigurationManager.AppSettings["url"];
            initBrowser();
        }
        public BrowserWindow(String url)
            : this()
        {
            this.mUrl = url;
            browser.Address = url;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //根据Key读取元素的Value
            string name = config.AppSettings.Settings["url"].Value;
            //写入元素的Value
            config.AppSettings.Settings["url"].Value = url;
            //一定要记得保存，写不带参数的config.Save()也可以
            config.Save(ConfigurationSaveMode.Modified);
            //刷新，否则程序读取的还是之前的值（可能已装入内存）
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void initBrowser()
        {
            var setting = new CefSettings();
            // 设置语言
            setting.Locale = "zh-CN";
            setting.CachePath = AppDomain.CurrentDomain.BaseDirectory + "Caches";
            //cef设置userAgent
            setting.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
            //CommandLine配置
            //setting.CefCommandLineArgs.Add("ppapi-flash-path", AppDomain.CurrentDomain.BaseDirectory + "Plugins\\pepflash\\pepflashplayer.dll");
            //setting.CefCommandLineArgs.Add("debug-plugin-loading", "1");
            //setting.CefCommandLineArgs.Add("allow-outdated-plugins", "1");
            //setting.CefCommandLineArgs.Add("always-authorize-plugins", "1");
            //setting.CefCommandLineArgs.Add("disable-web-security", "1");
            //setting.CefCommandLineArgs.Add("enable-npapi", "1");
            //setting.CefCommandLineArgs.Remove("enable-system-flash");
            //setting.CefCommandLineArgs.Add("enable-system-flash", "1");
            Cef.Initialize(setting, true, true);
            browser = new ChromiumWebBrowser();
            browser.BrowserSettings.PluginsDisabled = false;
            browser.Address = mUrl;
            InitializeComponent();
            this.grid.Children.Add(browser);
            Grid.SetRow(browser, 0);
            browser.IsBrowserInitializedChanged += browser_IsBrowserInitializedChanged;
            browser.LifeSpanHandler = new OpenPageSelf();
        }

        private void browser_IsBrowserInitializedChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            browser.WebBrowser.FrameLoadStart += WebBrowser_FrameLoadStart;
            browser.WebBrowser.FrameLoadEnd += WebBrowser_FrameLoadEnd;

        }

        private void WebBrowser_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(() => {
                this.loading.IsActive = false;
            }));
        }

        private void WebBrowser_FrameLoadStart(object sender, CefSharp.FrameLoadStartEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.loading.IsActive = true;
            }));
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            if (browser != null)
                browser.Dispose();
        }
    }
    /// <summary>
    /// 在自己窗口打开链接
    /// </summary>
    internal class OpenPageSelf : ILifeSpanHandler
    {
        public void OnBeforeClose(IWebBrowser browser)
        {
            Console.WriteLine(browser.Address);
        }

        public bool OnBeforePopup(IWebBrowser browser, string sourceUrl, string targetUrl, ref int x, ref int y, ref int width, ref int height)
        {
            browser.Load(targetUrl);
            return true;
        }
    }
}
